import {Axios} from '../utils/AxiosPlugin'
import PnDesigner from "../utils/PnDesigner";

/**
 * 代理请求
 * @param method 请求方式：GET、POST
 * @param apiPath 请求地址
 * @param headers 头信息
 * @param postData POST请求提交数据
 * @returns {Promise<AxiosResponse<any>>}
 */
const httpQuery = async function (method = 'GET', apiPath = '', headers = {}, postData = {}) {
  apiPath = PnDesigner.replaceStringSourceInteractionFields(apiPath);
  headers = PnDesigner.replaceObjectSourceInteractionFields(headers);
  postData = PnDesigner.replaceObjectSourceInteractionFields(postData);
  return await Axios.post('/httpProxy/httpQuery', {
    method: method, apiPath: apiPath, headers: JSON.stringify(headers), postData: JSON.stringify(postData)
  })
};

/**
 * 同步代理请求
 * @param method 请求方式：GET、POST
 * @param apiPath 请求地址
 * @param headers 头信息
 * @param postData POST请求提交数据
 * @returns {Promise<unknown>}
 */
const httpQuerySync = async function (method = 'GET', apiPath = '', headers = {}, postData = {}) {
  apiPath = PnDesigner.replaceStringSourceInteractionFields(apiPath);
  headers = PnDesigner.replaceObjectSourceInteractionFields(headers);
  postData = PnDesigner.replaceObjectSourceInteractionFields(postData);
  let promise = new Promise((resolve, reject) => {
    $.ajax({
      url: window.g.AXIOS_BASE_URL + '/httpProxy/httpQuery',
      type: 'POST',
      async: false,
      // dataType: 'json',
      data: {
        method: method,
        apiPath: apiPath,
        headers: JSON.stringify(headers),
        postData: JSON.stringify(postData)
      },
      contentType: 'application/json',
      success: (result) => {
        resolve(result)
      },
      error: (error) => {
        reject(error)
      }
    })
  })
  return promise
}

export default {
  httpQuery,
  httpQuerySync
}
